import 'dart:async';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_speech/flutter_speech.dart';
import 'package:go_router/go_router.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:widgets_to_image/widgets_to_image.dart';

import '../../../helper/my_widget.dart';
import '../../../lang/lang.dart';
import '../../../repo/model/gallery_home_model.dart';
import '../../component/dialog.dart';
import '../../component/loading.dart';

enum CreateStatus {
  prepare,
  rendering,
  model,
  proofreading,
  drawing,
  exporting,
}

class GalleryStartCreateScreen extends StatefulWidget {
  final SettingRepository setting;
  final int? styleId;
  final int sizeId;
  final String? title;
  final String? content;

  const GalleryStartCreateScreen({
    super.key,
    required this.setting,
    this.styleId,
    required this.sizeId,
    this.title,
    this.content,
  });

  @override
  State<GalleryStartCreateScreen> createState() =>
      _GalleryStartCreateScreenState();
}

class _GalleryStartCreateScreenState extends State<GalleryStartCreateScreen> {
  final WidgetsToImageController controller = WidgetsToImageController();
  CreateStatus _status = CreateStatus.prepare;
  late GalleryCreateModel _createModel;
  String _photoUrl = '';

  late Timer _timer;
  int timesp = -1;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (timesp >= 13) {
        if (timesp % 2 == 0) {
          monitorDrawResult();
        }
        timesp++;
        return;
      }
      if (timesp == 2) {
        _status = CreateStatus.prepare;
      } else if (timesp == 4) {
        _status = CreateStatus.rendering;
      } else if (timesp == 6) {
        _status = CreateStatus.model;
      } else if (timesp == 8) {
        _status = CreateStatus.proofreading;
      } else if (timesp == 10) {
        _status = CreateStatus.drawing;
      } else if (timesp >= 12) {
        _status = CreateStatus.exporting;
      }
      setState(() {
        timesp++;
      });
    });
    startDraw();
  }

  @override
  void dispose() {
    if (_timer != null && _timer.isActive) {
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;

    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.transparent,
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            centerTitle: true,
            elevation: 0,
            backgroundColor: Colors.transparent,
            title: MyTextWeight('图片生成', 18, Colors.white, FontWeight.normal),
            leading: IconButton(
              padding: const EdgeInsets.all(16),
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                if (context.canPop()) {
                  context.pop();
                }
              },
            ),
          ),
          body: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox(height: 25),
              Visibility(
                visible: isBlank(_photoUrl),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(left: 26, right: 26),
                      child: MyTextWeight(
                          '图片生成中', 20, Colors.white, FontWeight.w500),
                    ),
                    Padding(
                      padding:
                          const EdgeInsets.only(left: 26, right: 26, top: 12),
                      child: MyTextWeight(
                          '请稍作等待，生产中可以返回（大概消耗10-20秒左右）稍后可通过我的作品查看画画作品',
                          15,
                          Colors.white.withOpacity(0.8),
                          FontWeight.normal),
                    ),
                    Container(
                      decoration: const BoxDecoration(
                          image: DecorationImage(
                              image: AssetImage('images/shengchengzhong.png'))),
                      margin: const EdgeInsets.only(top: 40),
                      height: 263,
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          MyTextWeight(_getStatusTitle(), 17, Colors.white,
                              FontWeight.normal),
                          AnimatedTextKit(
                            repeatForever: true,
                            animatedTexts: [
                              TypewriterAnimatedText('...',
                                  speed: const Duration(milliseconds: 50),
                                  textStyle: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 17,
                                  )),
                            ],
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Visibility(
                visible: isNotBlank(_photoUrl),
                child: Container(
                    alignment: Alignment.topCenter,
                    width: double.infinity,
                    margin: const EdgeInsets.only(left: 22, right: 22),
                    constraints: BoxConstraints(
                        maxHeight: ScreenUtil().screenHeight - 25 - 36.w - 50 - 12 - 64 -
                            ScreenUtil().statusBarHeight),
                    child: IntrinsicWidth(
                      child: IntrinsicHeight(
                        child: ClipRRect(
                          // borderRadius: BorderRadius.circular(11),
                          child: WidgetsToImage(
                            controller: controller,
                            child: CachedNetworkImage(
                              // width: double.infinity,
                              // height: double.infinity,
                              placeholder: (context, url) => Center(
                                  child: CircularProgressIndicator(
                                      color: customColors.themeBlueColor)),
                              imageUrl: _photoUrl,
                              fit: BoxFit.fitWidth,
                              // imageBuilder: (context, imageProvider) => Container(
                              //   decoration: BoxDecoration(
                              //     color: Colors.red,
                              //       borderRadius: BorderRadius.circular(11),
                              //       image: DecorationImage(
                              //           image: imageProvider, fit: BoxFit.fitWidth))
                              // ),
                            ),
                          ),
                        ),
                      ),
                    )),
              ),
              Visibility(
                visible: isNotBlank(_photoUrl),
                child: const Spacer(),
              ),
              Visibility(
                visible: isNotBlank(_photoUrl),
                child: Container(
                  height: 50,
                  margin: EdgeInsets.only(left: 22, right: 22, bottom: 36.w),
                  width: double.infinity,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('images/guide_button.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                  child: CupertinoButton(
                    padding: EdgeInsets.zero,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        imgWidget(16, 17, 'xiazai'),
                        const SizedBox(width: 7),
                        MyTextWeight('下载图片', 16, Colors.white, FontWeight.w400),
                      ],
                    ),
                    onPressed: () async {
                      save();
                    },
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  String _getStatusTitle() {
    if (_status == CreateStatus.prepare) {
      return '正在准备画画';
    } else if (_status == CreateStatus.rendering) {
      return '正在渲染图片';
    } else if (_status == CreateStatus.model) {
      return '正在制作高清模型';
    } else if (_status == CreateStatus.proofreading) {
      return '正在校对图片逻辑';
    } else if (_status == CreateStatus.drawing) {
      return '正在画图';
    }
    return '正在输出图片';
  }

  void startDraw() {
    APIServer()
        .galleryStartDraw(
            widget.title, widget.content, widget.styleId, widget.sizeId)
        .then((value) {
      _createModel = value;
    });
  }

  void monitorDrawResult() {
    var id = _createModel.id ?? 0;
    APIServer().galleryCreateProgress(id).then((value) {
      if (isNotBlank(value.url ?? '')) {
        _timer.cancel();
        _photoUrl = value.url!;
        _createModel = value;
        setState(() {});
      }
    });
  }

  void save() async {
    PermissionStatus status = await Permission.photos.status;
    if (!status.isGranted) {
      // 请求权限
      status = await Permission.photos.request();
      if (!status.isGranted) {
        showCupertinoDialog(
            context: context,
            builder: (BuildContext context) {
              return CupertinoAlertDialog(
                title: const Text('提示'),
                content: const Text('您未授权访问相册，无法使用保存相册功能，请在设置中允许访问照片/相册权限后重试'),
                actions: [
                  CupertinoDialogAction(
                    isDefaultAction: true,
                    child: const Text(
                      '取消',
                      style: TextStyle(
                          color: Colors.white, fontWeight: FontWeight.normal),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  CupertinoDialogAction(
                    isDestructiveAction: true,
                    child: const Text('去设置'),
                    onPressed: () {
                      context.pop();
                      launchUrlString('App-Prefs:Privacy&path=PHOTOS');
                    },
                  ),
                ],
                insetAnimationDuration: const Duration(seconds: 2),
              );
            });

        return;
      }
    }


    EasyLoading.show(
        status: '请稍等...',
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false);
    try {
      final data = await controller.capture();
      EasyLoading.dismiss();
      if (data != null) {
        await ImageGallerySaver.saveImage(data, quality: 100);
        showSuccessMessage('已下载到手机，请通过相册查看');
      }
    } finally {
      EasyLoading.dismiss();
    }
  }
}
